package com.dgut.courses_selecting_sys.rabbitmq;

import com.alibaba.fastjson.JSON;
import com.dgut.courses_selecting_sys.constants.ActivityStatus;
import com.dgut.courses_selecting_sys.constants.RabbitMqKey;
import com.dgut.courses_selecting_sys.constants.RedisKey;
import com.dgut.courses_selecting_sys.entity.Activities;
import com.dgut.courses_selecting_sys.mapper.ActivitiesMapper;
import com.dgut.courses_selecting_sys.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@RabbitListener(queuesToDeclare = @Queue(value = RabbitMqKey.ACTIVITIES_PROCESS_QUEUE,durable = "true"))
public class ActivitiesStartConsumer {

    @Autowired
    ActivitiesMapper activitiesMapper;
    @Autowired
    RedisUtil redisUtil;
    @Autowired
    RedisTemplate redisTemplate;

    /**
     * 活动开选，修改数据库状态，并存入redis
     *
     * @param msg
     */
    @RabbitHandler()
    public void activityConsumer(String msg) {
        Long id = JSON.parseObject(msg, Long.class);
        Activities activities = activitiesMapper.selectById(id);
            if (activities.getStatus() == ActivityStatus.PRE) {
                //设置redis
                redisUtil.set(RedisKey.ACTIVITIES_SELECTED + id, activities, (activities.getStartTime().getTime() - activities.getSelectedTime().getTime()) / 1000);
                redisUtil.set(RedisKey.ACTIVITY_COUNT + activities.getActivityId(), activities.getCount(), (activities.getStartTime().getTime() - activities.getSelectedTime().getTime()) / 1000);
                activities.setStatus(ActivityStatus.START);
                activitiesMapper.updateById(activities);
                log.info("活动开选通知:" + activities);
            }

    }

}

